﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.ServiceModel;
using BookClubIt.Processor;
using DTO = BookClubIt.DTO;


namespace BookClubIt
{
    public partial class bookclub_default : BasePage
    {

        protected void Page_Load(object sender, EventArgs e)
        {
           string username = HttpContext.Current.User.Identity.Name.ToString();
           DTO.Member member = MemberProcessorInstance.GetMemberByUsername(username);
           int CurrentUserId = member.Id;

          DTO.BookClub club = BookClubProcessorInstance.GetBookClubById(CID);

          int genreTypeInt = club.GenreType;

         int clubTypeInt = club.ClubType;
         int clubId = club.Id;
         //    string currentASIN = club.CurrentBook;

         DTO.ClubType type = BookClubProcessorInstance.GetBookClubType(clubTypeInt);

            // if the club is secret and the current user is not a member of the club redirect to sign in.
         if (clubTypeInt == 3 && !BookClubProcessorInstance.IsBookClubMember(CurrentUserId, CID))
         {
             Response.Redirect("../login.aspx");
         }
          
         DTO.GenreType genre = BookClubProcessorInstance.GetBookClubGenre(genreTypeInt);
         lblClubGenre.Text = genre.GenreName;

         if (type.ClubTypeName == "Public")
             lblClubType.CssClass = "status public";

         if (type.ClubTypeName == "Private")
             lblClubType.CssClass = "status private";

         lblClubType.Text = type.ClubTypeName;

        //  lblClubType.Text = clubtype.Name;

          var club_Name = club.Name;
          lblClubName.Text = club.Name;
          Page.MetaDescription = club.Description;

          lblCreatedDate.Text = TimeAgo(club.CreatedDate);
          lblDescription.Text = club.Description;
          lblRules.Text = club.Rules;
          lblWebsite.Text = club.Website;

          DTO.Topics topic = BookClubProcessorInstance.GetDiscussionTopics(CID, true);
          if (topic.Count == 0)
          {
              pnlNoDiscussions.Visible = true;
              grdDiscussionTopics.Visible = false;
          }
          else
          {

              grdDiscussionTopics.DataSource = topic;
              grdDiscussionTopics.DataBind();

          }
         //  DTO.Book current = BookProcessorInstance.GetCurrentBook(bid);
        //   imgCurrentBook.ImageUrl = current.MediumImageURL;

          if (HttpContext.Current.User.Identity.IsAuthenticated && BookClubProcessorInstance.IsLeader(CurrentUserId, CID))
          {
              // do stuff if current user is leader

          }

            // get all the members in the book club
          DTO.Members members = MemberProcessorInstance.GetTopBookClubMembersById(CID);
            rptMemberList.DataSource = members;
            rptMemberList.DataBind();

            DTO.Members all_members = MemberProcessorInstance.GetBookClubMembersById(CID);
            lblMemberCount.Text = all_members.Count().ToString();
            lblMemberCountTop.Text = all_members.Count().ToString();

            DTO.Activities activities = BookClubProcessorInstance.GetTopActivityById(CID);
            grdActivityGrid.DataSource = activities;
            grdActivityGrid.DataBind();

            DTO.Meetings meetings = BookClubProcessorInstance.GetMeetings(CID);

            rptMeetingList.DataSource = meetings;
            rptMeetingList.DataBind();
            if (meetings.Count == 0)
            {
                pnlNoMeetings.Visible = true;
                rptMeetingList.Visible = false;
            }
          
        }
        public void BindData(DTO.Activities activities)
        {
            grdActivityGrid.DataSource = activities;
            grdActivityGrid.DataBind();
        }

        protected void grdActivityGrid_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            DTO.Activity activity = e.Row.DataItem as DTO.Activity;

            int tid = 0;
            int.TryParse(Request.QueryString["tid"], out tid);

    
            string username = HttpContext.Current.User.Identity.Name;
            DTO.Member memberbyusername = MemberProcessorInstance.GetMemberByUsername(username);
            int CurrentUserId = memberbyusername.Id;

            if (e.Row.RowType != DataControlRowType.DataRow)
                return;

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                HyperLink lnkMember = ((HyperLink)e.Row.FindControl("lnkMember"));
                Image imgMemberAvatar = ((Image)e.Row.FindControl("imgMemberAvatar"));
                Label lblTypeAction = ((Label)e.Row.FindControl("lblTypeAction"));
                Label lblActionDate = ((Label)e.Row.FindControl("lblActionDate"));

                DTO.Member member = MemberProcessorInstance.GetMemberById(activity.User_Id);

                if (activity.Type == "JOINED")
                {
                    lblTypeAction.Text = "joined this book club.";
                }
                if (activity.Type == "ADDLEADER")
                {
                    lblTypeAction.Text = "became a leader.";
                }
                if (activity.Type == "CHANGEBOOK")
                {
                    DTO.Book book = BookProcessorInstance.GetBookById(activity.Data);
                    lblTypeAction.Text = "changed the current book to <a href='../book.aspx?id=" + book.Id + "'>" + book.Title + "</a>";
                }
                if (activity.Type == "CREATED")
                {
                    lblTypeAction.Text = "created this book club.";
                }
                if (activity.Type == "REMOVEBOOK")
                {
                    DTO.Book book = BookProcessorInstance.GetBookById(activity.Data);
                    lblTypeAction.Text = "removed the book <a href='../book.aspx?id=" + book.Id + "'>" + book.Title + "</a> from the shelf.";
                }
                if (activity.Type == "ADDTOPIC")
                {
                    DTO.Topic topic = BookClubProcessorInstance.GetDiscussionTopicById(activity.Data);
                    lblTypeAction.Text = "added a discussion topic";
                }
                if (activity.Type == "ADDCOMMENT")
                {

                    DTO.Topic topic = BookClubProcessorInstance.GetDiscussionTopicById(activity.Data);
                    lblTypeAction.Text = "added a comment to <a href='topic.aspx?id=" + CID + "&tid=" + topic.Id + "'>" + topic.Topic_Name + "</a>";

                }
                if (activity.Type == "ADDBOOK")
                {

                    DTO.Book book = BookProcessorInstance.GetBookById(activity.Data);
                    lblTypeAction.Text = "added <a href='../book.aspx?id=" + book.Id + "'>" + book.Title + "</a> to the book shelf.";

                }
                if (activity.Type == "UNJOIN")
                {
                    lblTypeAction.Text = "left this book club.";
                }
                lblActionDate.Text = TimeAgo(activity.Time).ToString();

                lnkMember.Text = member.Username.ToString();
                lnkMember.NavigateUrl = "../member.aspx?uid=" + member.Id;
                imgMemberAvatar.ImageUrl = "../avatars/" + member.AvatarURL;

            }
        }

        public void BindData(DTO.Topics topics)
        {
            grdDiscussionTopics.DataSource = topics;
            grdDiscussionTopics.DataBind();
        }
       
        protected void grdDiscussionTopics_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            DTO.Topic topic = e.Row.DataItem as DTO.Topic;


            hdnBid.Value = CID.ToString();

            if (e.Row.RowType != DataControlRowType.DataRow)
                return;

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                HyperLink lnkTopic = ((HyperLink)e.Row.FindControl("lnkTopic"));
                HyperLink lnkLatestCommentMember = ((HyperLink)e.Row.FindControl("lnkLatestCommentMember"));
                Label lblPostCount = ((Label)e.Row.FindControl("lblPostCount"));
                Label lblPostAbout = ((Label)e.Row.FindControl("lblPostAbout"));
                Label lblRecentActivity = ((Label)e.Row.FindControl("lblRecentActivity"));

                int tid = topic.Id;

                DTO.Comments getComments = BookClubProcessorInstance.GetTopicComments(tid);

                lnkTopic.NavigateUrl = "topic.aspx?id=" + hdnBid.Value + "&tid=" + tid;
                lnkTopic.Text = topic.Topic_Name;
                DTO.Book postaboutbook = BookProcessorInstance.GetBookByASIN(topic.ASIN);
                lblPostAbout.Text = postaboutbook.Title;

                lblPostCount.Text = getComments.Count.ToString();

                DTO.Comment getLatestComment = BookClubProcessorInstance.GetLatestComment(tid);
                DTO.Member membercomment = MemberProcessorInstance.GetMemberById(getLatestComment.User_Id);

                if (getComments.Count == 0)
                {
                    lblRecentActivity.Text = "No comments";
                    lnkLatestCommentMember.Visible = false;
                }
                else
                {
                    lblRecentActivity.Text = TimeAgo(getLatestComment.Comment_Date).ToString() + " by ";
                    lnkLatestCommentMember.NavigateUrl = "../member.aspx?uid=" + membercomment.Id;
                    lnkLatestCommentMember.Text = membercomment.Username;
                }
            }
        }

        protected void rptMeetingList_OnItemDataBound(object sender, RepeaterItemEventArgs e)
        {

            RepeaterItem item = e.Item; if (item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.Item)
            {
                DTO.Meeting meeting = e.Item.DataItem as DTO.Meeting;

                HyperLink lnkMeetingLink = (HyperLink)item.FindControl("lnkMeetingLink");

                lnkMeetingLink.NavigateUrl = "meetingdetail.aspx?id=" + CID + "&mid="+ meeting.Id;
                lnkMeetingLink.Text = meeting.Title;
            }

        }

        static string TimeAgo(DateTime time)
        {
            DateTime startDate = DateTime.Now;
            TimeSpan deltaMinutes = startDate.Subtract(time);
            string distance = string.Empty;
            if (deltaMinutes.TotalMinutes <= (8724 * 60))
            {
                distance = DistanceOfTimeInWords(deltaMinutes.TotalMinutes);
                if (deltaMinutes.Minutes < 0)
                {
                    return distance + " from  now";
                }
                else
                {
                    return distance + " ago";
                }
            }
            else
            {
                return "on " + time.ToString();
            }
        }
        static string DistanceOfTimeInWords(double minutes)
        {
            if (minutes < 1)
            {
                return "less than a minute";
            }
            else if (minutes < 50)
            {
                return Math.Round(minutes).ToString() + " minutes";
            }
            else if (minutes < 90)
            {
                return "about one hour";
            }
            else if (minutes < 1080)
            {
                return Math.Round(new decimal((minutes / 60))).ToString() + " hours";
            }
            else if (minutes < 1440)
            {
                return "one day";
            }
            else if (minutes < 2880)
            {
                return "about one day";
            }
            else
            {
                return Math.Round(new decimal((minutes / 1440))).ToString() + " days";
            }
        }

        protected string FormatAvatar(object oItem)
        {
            string url = DataBinder.Eval(oItem, "AvatarURL").ToString().Trim();
            return url;    
        }


        }

    }
